#include "tree_widget.h"
#include "easylogging++.h"
#include <QMimeData>
#include <QDropEvent>

TreeWidget::TreeWidget(QWidget *parent) : QTreeWidget(parent)
{

}

bool TreeWidget::dropMimeData(QTreeWidgetItem *parent, int index, const QMimeData *data, Qt::DropAction action)
{
    if (nullptr == parent)
    {
        LOG(DEBUG) << "parent is nullptr...";
        return true;
    }

    if (nullptr == data)
    {
        LOG(DEBUG) << "mimedata is nullptr...";
        return true;
    }

    LOG(DEBUG) << "data: " << data->text().toStdString();

    LOG(DEBUG) << "drop action: " << action;

    return true;
}

void TreeWidget::dropEvent(QDropEvent *event)
{
    LOG(DEBUG) << "drop event enter...";
    auto selItemList = this->selectedItems();
    LOG(DEBUG) << "selected item size: " << selItemList.size();
    if (selItemList.size() <1)
    {
        return;
    }
    auto curItem = selItemList.first();
    if (curItem == nullptr)
    {
        return;
    }
    LOG(DEBUG) << "current item: " << curItem->text(0).toStdString();
    auto parentItem = curItem->parent();
    if (parentItem  == nullptr)
    {
        LOG(DEBUG) << "current item parent is root";
        this->takeTopLevelItem(this->indexOfTopLevelItem(curItem));
    }
    else
    {
        LOG(DEBUG) << "current item parent is " << parentItem->text(0).toStdString();
        parentItem->removeChild(curItem);
    }
    auto item = this->itemAt(event->pos());
    if (item  == nullptr)
    {
        LOG(DEBUG) << "move current item to root";
        this->addTopLevelItem(curItem);
    }
    else
    {
        LOG(DEBUG) << "move current item to " << item->text(0).toStdString();
        item->addChild(curItem);
    }

    emit(itemIsMoved(curItem));

    LOG(DEBUG) << "drop event out...";
}
